import Vue from 'vue'
const drag = Vue.directive('drag', {
  inserted (el, binding) {
    let oDiv = el
    // 左边距最大值
    let maxLeft = window.screen.width - el.clientWidth
    // 上边距最大值
    let maxTop = window.screen.height - el.clientHeight
    oDiv.ontouchstart = function (e) {
      // 鼠标按下，计算当前元素距离可视区的距离
      let disX = e.touches[0].clientX - oDiv.offsetLeft
      let disY = e.touches[0].clientY - oDiv.offsetTop
      document.ontouchmove = function (e) {
        // 获取到鼠标拖拽后的横向位移(距离父级元素)
        let l = e.touches[0].clientX - disX
        // 获取到鼠标拖拽后的纵向位移(距离父级元素)
        let t = e.touches[0].clientY - disY
        oDiv.style.left = l + 'px'
        oDiv.style.top = t + 'px'
        if (e.touches[0].clientX - disX <= 0) {
          oDiv.style.left = 0 + 'px'
        }
        if (e.touches[0].clientY - disY <= 0) {
          oDiv.style.top = 0 + 'px'
        }
        if (e.touches[0].clientX - disX >= maxLeft) {
          oDiv.style.left = maxLeft + 'px'
        }
        if (e.touches[0].clientY - disY >= maxTop) {
          oDiv.style.top = maxTop + 'px'
        }
      }
      // 松开事件后，移除事件
      document.ontouchend = function (e) {
        document.ontouchmove = null
        document.ontouchend = null
      }
    }
  }
})
// function stopTouchendPropagationAfterScroll () {
//   var locked = false
//   window.addEventListener('touchmove', function (ev) {
//     locked || (locked = true, window.addEventListener('touchend', stopTouchendPropagation, true))
//   }, true)
//   function stopTouchendPropagation (ev) {
//     ev.stopPropagation()
//     window.removeEventListener('touchend', stopTouchendPropagation, true)
//     locked = false
//   }
// }
export default{
  drag
}
